import 'package:flutter/material.dart';
import 'package:xiaozhoubg/service/service_method.dart';
import '../../config/service_url.dart';
import 'package:dio/dio.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:html/dom.dart' as dom;
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

class BookDocs extends StatefulWidget {
  Map arguments;
  BookDocs({Key key, this.arguments}) : super(key: key);

  @override
  _BookDocsState createState() => _BookDocsState(arguments);
}

class _BookDocsState extends State<BookDocs> {
  Future saveDocs(String docs) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    print("本地缓存节名：$docs");
    sharedPreferences.setString("docs", docs);
  }

  Future saveDocsid(String id) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    print("本地缓存节id：$id");

    sharedPreferences.setString("docsid", id);
  }

  getlast() {
    getlastDocs(id).then((value) {
      setState(() {
        print("sss");
        this.docs = value['htmlContent'];
        this.id = value['id'];
      });
    });
  }

  getnext() {
    getnextDocs(id).then((value) {
      setState(() {
        print("sss");
        this.docs = value['htmlContent'];
        this.id = value['id'];
      });
    });
  }

  _BookDocsState(this.arguments);
  Map arguments;
  String docs;
  Map data;
  String id;
  List bookcatalogList;
  List sectionList;
  bool iflast;
  bool ifnext;
  @override
  void initState() {
    setState(() {
      this.bookcatalogList = this.arguments['bookCatalogList'];
      this.sectionList = this.arguments['sectionList'];
    });
    super.initState();
    getBookDocs(arguments['id']).then((value) {
      setState(() {
        this.docs = value['data']['htmlContent'];
        this.id = value['data']['id'].toString();
        this.iflast = value['iflast'];
        this.ifnext = value['ifnext'];
        print(this.id);
        print(this.docs);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        leading: IconButton(
            icon: Icon(
              Icons.keyboard_arrow_left,
              size: 30,
              color: Colors.black,
            ),
            onPressed: () {
              Navigator.of(context).pop();
            }),
        backgroundColor: Color.fromRGBO(242, 242, 242, 1),
        actions: <Widget>[
          FlatButton(
            color: Color.fromRGBO(242, 242, 242, 1),
            onPressed: () {
              print("用户点击了收藏按钮");
            },
            child: Text("收藏"),
          )
        ],
      ),
      body: Container(
        height: ScreenUtil().setHeight(1026),
        child: SingleChildScrollView(
          child: Html(
            data: """
            $docs
  """,
            //Optional parameters:
            padding: EdgeInsets.all(8.0),
            linkStyle: const TextStyle(
              color: Colors.redAccent,
              decorationColor: Colors.redAccent,
              decoration: TextDecoration.underline,
            ),
            onLinkTap: (url) {
              print("Opening $url...");
            },
            onImageTap: (src) {
              print(src);
            },
            //Must have useRichText set to false for this to work
            customRender: (node, children) {
              if (node is dom.Element) {
                switch (node.localName) {
                  case "custom_tag":
                    return Column(children: children);
                }
              }
              return null;
            },
            customTextAlign: (dom.Node node) {
              if (node is dom.Element) {
                switch (node.localName) {
                  case "p":
                    return TextAlign.justify;
                }
              }
              return null;
            },
            customTextStyle: (dom.Node node, TextStyle baseStyle) {
              if (node is dom.Element) {
                switch (node.localName) {
                  case "p":
                    return baseStyle.merge(TextStyle(height: 2, fontSize: 20));
                }
              }
              return baseStyle;
            },
          ),
        ),
      ),
      bottomNavigationBar: Container(
        height: ScreenUtil().setHeight(80),
        child: Builder(
          builder: (context) {
            return Scaffold(
              appBar: AppBar(
                backgroundColor: Color.fromRGBO(242, 242, 242, 1),
                leading: IconButton(
                  icon: Icon(Icons.keyboard_arrow_left),
                  onPressed: this.iflast
                      ? () {
                          this.getlast();
                        }
                      : null,
                ),
                title: InkWell(
                  child: Text(
                    "目录",
                    style: TextStyle(color: Colors.black),
                  ),
                  onTap: () {
                    showBottomSheet(
                      context: context,
                      builder: (_) => Container(
                        height: 500,
                        decoration: BoxDecoration(
                            color: Color.fromRGBO(247, 247, 247, 1)),
                        child: SingleChildScrollView(
                          child: Column(
                            children: <Widget>[
                              Container(
                                height: 450,
                                child: ListView.builder(
                                  itemCount: this.bookcatalogList.length,
                                  itemBuilder: (context, index) {
                                    var sections = _getSections(
                                        this.sectionList,
                                        "${this.bookcatalogList[index]['id']}");
                                    return ExpansionTile(
                                      title: Text(
                                          "${this.bookcatalogList[index]['name']}"),
                                      children: sections,
                                    );
                                  },
                                ),
                              ),
                              FlatButton(
                                onPressed: () {
                                  Navigator.of(context).pop();
                                },
                                child: Text("取消"),
                              )
                            ],
                          ),
                        ),
                      ),
                    );
                  },
                ),
                centerTitle: true,
                actions: <Widget>[
                  IconButton(
                      icon: Icon(Icons.keyboard_arrow_right),
                      onPressed: this.ifnext
                          ? () {
                              this.getnext();
                            }
                          : null)
                ],
              ),
            );
          },
        ),
      ),
    );
  }

  _getSections(list, chaperid) {
    List<Widget> widgets = [];
    if (list != null && (list as List).length > 0) {
      (list as List).forEach((f) {
        if ("${f['chapterId']['id']}" == chaperid) {
          widgets.add(
            InkWell(
              child: ListTile(
                title: Text("${f['name']}"),
              ),
              onTap: () {
                this.saveDocs("${f['name']}");
                this.saveDocsid("${f['id']}");
                Navigator.pushNamed(context, '/bookdocs', arguments: {
                  "id": "${f['id']}",
                  "bookCatalogList": this.bookcatalogList,
                  "section": this.sectionList,
                });
                print("${f['id']}");
              },
            ),
          );
        }
      });
    }
    return widgets;
  }
}
